import { Card, CardBody, CardHeader, Input, Button, Avatar } from "@heroui/react";
import { useState, useRef, useEffect } from "react";

import DefaultLayout from "@/layouts/default";

export default function ChatPage() {
  // Mock data for chat contacts
  const contacts = [
    { id: 1, name: "张三", avatar: "", status: "online", lastMessage: "好的，明天见", time: "10:30" },
    { id: 2, name: "李四", avatar: "", status: "online", lastMessage: "项目进展如何？", time: "09:45" },
    { id: 3, name: "王五", avatar: "", status: "away", lastMessage: "稍后回复你", time: "昨天" },
    { id: 4, name: "赵六", avatar: "", status: "offline", lastMessage: "谢谢你的帮助", time: "昨天" },
    { id: 5, name: "孙七", avatar: "", status: "online", lastMessage: "会议时间改了", time: "前天" },
  ];

  // Mock data for chat messages
  const initialMessages = [
    { id: 1, sender: "张三", content: "你好，今天的工作进展如何？", time: "10:25", isMe: false },
    { id: 2, sender: "我", content: "进展顺利，已完成80%的任务", time: "10:26", isMe: true },
    { id: 3, sender: "张三", content: "很好，继续保持", time: "10:27", isMe: false },
    { id: 4, sender: "我", content: "好的，我会的", time: "10:28", isMe: true },
    { id: 5, sender: "张三", content: "明天下午有个会议，记得参加", time: "10:30", isMe: false },
  ];

  const [messages, setMessages] = useState(initialMessages);
  const [newMessage, setNewMessage] = useState("");
  const [activeContact, setActiveContact] = useState(contacts[0]);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Auto scroll to bottom when messages change
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const handleSendMessage = () => {
    if (newMessage.trim() === "") return;

    const message = {
      id: messages.length + 1,
      sender: "我",
      content: newMessage,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      isMe: true
    };

    setMessages([...messages, message]);
    setNewMessage("");
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <DefaultLayout>
      <div className="flex flex-col h-[calc(100vh-120px)] py-6">
        {/* Page Title */}
        <div className="flex flex-col gap-2 mb-6">
          <h1 className="text-2xl font-bold">聊天</h1>
          <p className="text-default-500">与团队成员实时沟通</p>
        </div>

        {/* Chat Container */}
        <Card className="flex flex-1 flex-col shadow-sm h-full">
          <CardBody className="p-0 flex flex-1">
            <div className="flex h-full">
              {/* Contacts Sidebar */}
              <div className="w-1/3 border-r border-default-200 flex flex-col">
                <CardHeader className="pb-4">
                  <h2 className="text-lg font-semibold">联系人</h2>
                </CardHeader>
                <div className="flex-1 overflow-y-auto">
                  {contacts.map((contact) => (
                    <div 
                      key={contact.id}
                      className={`flex items-center gap-3 p-4 cursor-pointer hover:bg-default-100 ${
                        activeContact.id === contact.id ? "bg-default-200" : ""
                      }`}
                      onClick={() => setActiveContact(contact)}
                    >
                      <div className="relative">
                        <Avatar 
                          name={contact.name} 
                          size="md" 
                          showFallback
                        />
                        <div className={`absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-white ${
                          contact.status === "online" 
                            ? "bg-success" 
                            : contact.status === "away" 
                              ? "bg-warning" 
                              : "bg-default"
                        }`}></div>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex justify-between items-center">
                          <p className="font-medium truncate">{contact.name}</p>
                          <span className="text-xs text-default-500">{contact.time}</span>
                        </div>
                        <p className="text-sm text-default-500 truncate">{contact.lastMessage}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Chat Area */}
              <div className="flex-1 flex flex-col">
                {/* Chat Header */}
                <CardHeader className="border-b border-default-200">
                  <div className="flex items-center gap-3">
                    <Avatar 
                      name={activeContact.name} 
                      size="md" 
                      showFallback
                    />
                    <div>
                      <p className="font-medium">{activeContact.name}</p>
                      <p className="text-sm text-default-500">
                        {activeContact.status === "online" 
                          ? "在线" 
                          : activeContact.status === "away" 
                            ? "离开" 
                            : "离线"}
                      </p>
                    </div>
                  </div>
                </CardHeader>

                {/* Messages Area */}
                <div className="flex-1 overflow-y-auto p-4">
                  <div className="space-y-4">
                    {messages.map((message) => (
                      <div 
                        key={message.id} 
                        className={`flex ${message.isMe ? "justify-end" : "justify-start"}`}
                      >
                        <div 
                          className={`max-w-xs md:max-w-md px-4 py-2 rounded-2xl ${
                            message.isMe 
                              ? "bg-primary text-white rounded-br-none" 
                              : "bg-default-200 text-default-800 rounded-bl-none"
                          }`}
                        >
                          <p>{message.content}</p>
                          <div 
                            className={`text-xs mt-1 ${
                              message.isMe ? "text-primary-200" : "text-default-500"
                            }`}
                          >
                            {message.time}
                          </div>
                        </div>
                      </div>
                    ))}
                    <div ref={messagesEndRef} />
                  </div>
                </div>

                {/* Message Input */}
                <div className="border-t border-default-200 p-4">
                  <div className="flex gap-2">
                    <Input
                      fullWidth
                      placeholder="输入消息..."
                      value={newMessage}
                      onChange={(e) => setNewMessage(e.target.value)}
                      onKeyDown={handleKeyPress}
                      className="flex-1"
                    />
                    <Button 
                      color="primary" 
                      onClick={handleSendMessage}
                      isDisabled={newMessage.trim() === ""}
                    >
                      发送
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </CardBody>
        </Card>
      </div>
    </DefaultLayout>
  );
}